<?php
/**
 * Author: lf
 * Blog: https://blog.feehi.com
 * Email: job@feehi.com
 * Created at: 2017-07-09 00:59
 */

namespace common\helpers;


use api\models\User;

class StringHelper extends \yii\helpers\StringHelper
{

    /**
     * 返回utf8编码的字符串
     *
     * @param $str
     * @return string
     */
    public static function encodingWithUtf8($str)
    {
        $cur_encoding = mb_detect_encoding($str);
        if ($cur_encoding == "UTF-8" && mb_check_encoding($str, "UTF-8")) {
            return $str;
        } else {
            return utf8_encode($str);
        }
    }
    
    public static function getModelClassName($model_class){
    	if(!empty($model_class)){
    		$arr = explode('\\',$model_class);
    		$model_class = end($arr);
	    }
	    return $model_class;
    }
	
	public static function getErrorSummary($errors)
	{
		if(empty($errors)){
			return '';
		}
		
		if(is_string($errors)){
			return $errors;
		}
		$msg = '';
		if(is_array($errors)){
			foreach ($errors as $error) {
				$msg .= '【'. implode(' | ',$error).'】';
			}
		}
		
		return $msg;
	}
	
	
	public static function removeEmoji($str){
		$str = trim($str);
		$str = preg_replace_callback('/./u',function(array $match){
			return strlen($match[0]) >= 4 ? '' : $match[0];
		},$str);
		if (empty($str)) {//用户名为空，则随机
			$str = '***'.rand(100000,999999).'***';
		}
		if (User::findOne(['username' => $str])) {
			//用户存在，也随机
			$str = $str.rand(100000,999999);
		}
		return $str;
	}
}